package com.koron.css2.baseConfig.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.bean.ManageAreaBean;
import com.koron.css2.baseConfig.mapper.ManageAreaMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

/**
 * 添加管理区域
 * @author 李攀
 *
 */
public class ManageAreaAdd implements ServerInterface {
	
	private static Logger logger = LogManager.getLogger(ManageAreaAdd.class);
	
	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		ManageAreaMapper mapper = factory.getMapper(ManageAreaMapper.class);
		ManageAreaBean bean = null;
		try {
			bean = JsonUtils.objectToPojo(req.getData(), ManageAreaBean.class);
			bean.setManageAreaId(new ObjectId().toHexString());
			bean.setCreateName(userInfo.getUserInfo().getName());
			bean.setCreateTime(CommonUtils.getCurrentTime());
			handCode(mapper, bean);
			mapper.saveManageArea(bean);
		} catch (Exception e) {
			logger.error("非法参数",e);
			return MessageBean.create(Constant.ILLEGAL_PARAMETER, "非法参数", void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
	}
	
	/**
	 * 自动生成分级code
	 * @param mapper
	 * @param bean
	 */
	public static void handCode(ManageAreaMapper mapper,ManageAreaBean bean) {
		//生成code, 规则5位一级，下级自动继承上级
		String parentCode="";
		ManageAreaBean parentBean=null;
		if(StringUtils.isNotBlank(bean.getParentId()) && !bean.getParentId().equals("0")) {
			parentBean = mapper.findManageAreaById(bean.getParentId()); //通过id查询数据
			parentCode = parentBean.getAreaNo();
		}
		//取父级目录下最大的下级目录
		String maxCode = mapper.findMaxChild(parentCode);//通过行政区域编号查询
		if(StringUtils.isBlank(maxCode)) {//如果未找到，说明下面没有子级，给初始值
			maxCode = parentCode+"00000";
		}
		//未位加1
		long last5 = Long.parseLong("1"+maxCode.substring(maxCode.length()-5))+1;
		maxCode = maxCode.substring(0, maxCode.length()-5)+(last5+"").substring(1);		
		//重设code
		bean.setAreaNo(maxCode);
		
//		SelectBean selectBean = mapper.findManageAreaByCode(parentCode+"00001");
//		if(selectBean!=null){
//			//bean.setIsLeaf(selectBean.getIsLeaf());
//		}else{
//			bean.setIsLeaf(1);
//		}
		
		bean.setIsLeaf(1);//新增加的数据，都是叶结点
		//自动更新其上级为目录
		if(parentBean != null) {
			parentBean.setIsLeaf(0);
			parentBean.setUpdateTime(CommonUtils.getCurrentTime());
			mapper.updateManageArea(parentBean);
		}
	}

}
